<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>原生ajax请求</title>
</head>

<body>
  <script>
    // ajax四步：创建XMLHttpRequest对象，连接服务器，发送请求，接收响应数据
    function ajax(options) {
      options = options || {};
      options.type = (options.type || "GET").toUpperCase();
      options.dataType = options.dataType || 'json';
      var xhr = new XMLHttpRequest();
      var arr = [];
      if (options.params) {
        for (var key in options.params) {
          arr.push(encodeURIComponent(key) + "=" + encodeURIComponent(options.params[key]))
        }
        var postData = arr.join("&")
        options.url = options.url + "?" + postData
      }
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          var status = xhr.status;
          if (status >= 200 && status < 300) {
            try {
              options.success && options.success(JSON.parse(xhr.responseText))
            } catch (e) {
              options.success && options.success(xhr.responseText)
            }
          } else {
            options.fail && options.fail(status)
          }
        }
      }
      if (options.type == "GET") {
        xhr.open("GET", options.url, true)
        xhr.send(null)
      } else if (options.type == "POST") {
        xhr.open("POST", options.url, true)
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.send(JSON.stringify(options.data))
      }
    }


    ajax({
      url: '/login',
      type: 'POST',
      params: {
        Phone: 'phone'
      },
      success: function (response) {

      },
      fail: function (status) {

      }
    })
  </script>
</body>

</html>
